import { Blog } from '../model/Blog.js'
import {Op} from 'sequelize'

let fn_list = async (ctx, next) => {
  // 根据查询字符串 获取keyword数据
  let keyword = ctx.request.query.keyword || ''
  // console.log(keyword);  
  let where = null
  // 数据库根据关键字查询对应信息
  if(keyword.trim()){
    where = {
      [Op.or]:{
        title:{
          [Op.like]:`%${keyword}%`
        },
        author:{
          [Op.like]:`%${keyword}%`
        }
      }
    }
  }
  // 查询完成，返回结果
  // 根据条件向数据库中筛选
  let blogs = await Blog.findAll({where})
  ctx.body = {
    code: 1000,
    msg: '查询成功',
    data: blogs
  }
}
let fn_getById = async (ctx, next) => {
  let id = +ctx.params.id || 0
  let blogs = await Blog.findByPk(id)
  if (blogs) {
    ctx.body = {
      code: 1000,
      msg: '查询成功',
      data: blogs
    }
  } else {
    ctx.body = {
      code: 1000,
      msg: '查询失败',
      data: null
    }
  }
}
let fn_add = async (ctx, next) => {
  let obj = ctx.request.body
  // let idx = Blog[Blog.length - 1].id + 1
  // obj.id = idx
  Blog.create(obj)
  ctx.body = {
    code: 1000,
    msg: '新增成功',
    data: obj
  }
}
let fn_edit = async (ctx, next) => {
  let id = +ctx.params.id || 0
  let blogs = await Blog.findByPk(id)
  if (blogs) {
    let obj = ctx.request.body
    await Blog.update(obj, {
      where: {
        id: id
      }
    })
    ctx.body = {
      code: 1000,
      msg: '修改成功',
      data: obj
    }
  } else {
    ctx.body = {
      code: 1404,
      msg: '修改失败',
      data: null
    }
  }
}
let fn_del = async (ctx, next) => {
  let id = +ctx.params.id || 0
  let blogs = await Blog.findByPk(id)
  if (blogs) {
    await Blog.destroy({
      where: {
        id: id
      }
    })
    ctx.body = {
      code: 1000,
      msg: '删除成功',
      data: blogs
    }
  } else {
    ctx.body = {
      code: 404,
      msg: '删除失败'
    }
  }
}

export default [
  {
    method: 'get',
    url: '/blogs',
    fn: fn_list
  },
  {
    method: 'get',
    url: '/blogs/:id',
    fn: fn_getById
  },
  {
    method: 'post',
    url: '/blogs',
    fn: fn_add
  },
  {
    method: 'put',
    url: '/blogs/:id',
    fn: fn_edit
  },
  {
    method: 'delete',
    url: '/blogs/:id',
    fn: fn_del
  }
]